var AV = require('leanengine');
var _ = require('lodash');
var debug = require('debug')('app');
var router = require('express').Router();
var Restful = require('../index').restful();

var Objects = require('./AVObjects');

router.route("/")
  .get(function (req, resp) {
    var rest = Restful.instance(req, resp, Objects.UserRole);
    rest.doList(Objects);
  })
  .post(function (req, resp) {
    var error = check(req);
    if (error) {
      Response.clientError(resp, error);
      return;
    }

    var rest = Restful.instance(req, resp, Figure);
    var query = rest.query();
    query.equalTo("username", req.body.username);
    rest.assertCount(query, rest.class.k_title + '名已存在', 0)
      .done(function () {
        var user = rest.object();
        fill(user, req);
        return fillRoles(user, req, resp);
      }).done(function (entity) {
        rest.doSave(entity);
      });
  });

router.route("/:id")
  .get(function (req, resp) {
    Restful.instance(req, resp, Objects.User).doGet();
  })
  .put(function (req, resp) {
    var rest = Restful.instance(req, resp, Objects.User);
    rest.assertExist(req.body.id)
      .done(function (entity) {
        return fillRoles(entity, req, resp)
      }).done(function (entity) {
        rest.doSave(entity);
      });
  })
  .delete(function (req, resp) {
    Restful.instance(req, resp, Objects.User).doDelete();
  });




router.get('/*', function (req, res) {
  return res.status(403).end();
});

module.exports = router;